package com.yunc.modules.cms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunc.base.controller.CommonController;
import com.yunc.common.utils.R;
import com.yunc.modules.cms.entity.CmsArticle;
import com.yunc.modules.cms.entity.CmsArticleCategory;
import com.yunc.modules.cms.service.ICmsArticleCategoryService;
import com.yunc.modules.cms.service.ICmsArticleService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 文章管理
 *
 * @author congcong tao
 * @date 2018/12/3 17:36
 */
@RestController
@RequestMapping("cmsArticle")
public class CmsArticleController extends CommonController {

    private static final Logger logger = LogManager.getLogger(CmsArticleController.class);

    @Autowired
    private ICmsArticleService cmsArticleService;
    @Autowired
    private ICmsArticleCategoryService cmsArticleCategoryService;

    @GetMapping("/page")
    public R page(Page<CmsArticle> page, CmsArticle cmsArticle){
        IPage<CmsArticle> cmsArticlePage = cmsArticleService.pageInfo(page, cmsArticle);
        return R.ok().put("data", cmsArticlePage.getRecords()).put("count", cmsArticlePage.getTotal());
    }

    @GetMapping("/info")
    public R info(@RequestParam(required = false) Long id){
        CmsArticle cmsArticle = cmsArticleService.getEntityById(id);
        return R.ok().put("cmsArticle", cmsArticle);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody CmsArticle cmsArticle){
        cmsArticle.setCreateUser(getUserId());
        cmsArticle.setCreateTime(new Date());
        boolean flag = cmsArticleService.save(cmsArticle);
        if (flag) {
            Long id = cmsArticle.getId();
            boolean articleCategoryFlag = cmsArticleCategoryService.insertList(id, cmsArticle.getCategoryIds());
            if (articleCategoryFlag) {
                return R.ok();
            }
        }
        return R.error();
    }

    @PutMapping("/update")
    public R update(@RequestBody CmsArticle cmsArticle){
        Long id = cmsArticle.getId();
        cmsArticle.setCreateTime(new Date());
        boolean flag = cmsArticleService.updateById(cmsArticle);
        if (flag) {
            // 删除权限
            CmsArticleCategory record = new CmsArticleCategory();
            record.setArticleId(id);
            boolean removeFlag = cmsArticleCategoryService.remove(new QueryWrapper<>(record));
            boolean articleCategoryFlag = cmsArticleCategoryService.insertList(id, cmsArticle.getCategoryIds());
            if (removeFlag && articleCategoryFlag) {
                return R.ok();
            }
        }
        return R.error();
    }

}
